package com.nnnu.wsnackshop.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collection;

/**
 * 请求日志过滤器，用于调试跨域问题
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class RequestLoggingFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        String requestUrl = request.getRequestURI();
        String method = request.getMethod();
        String origin = request.getHeader("Origin");
        String referer = request.getHeader("Referer");

        // 确保跨域头信息被添加
        if (origin != null) {
            response.setHeader("Access-Control-Allow-Origin", origin);
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers",
                    "Origin, X-Requested-With, Content-Type, Accept, Authorization");
            response.setHeader("Access-Control-Max-Age", "3600");
        }

        // 对于OPTIONS请求，直接返回200
        if ("OPTIONS".equalsIgnoreCase(method)) {
            response.setStatus(HttpServletResponse.SC_OK);
            log.info("OPTIONS请求已处理并返回200");

            // 记录响应头
            logResponseHeaders(response);
            return;
        }

        filterChain.doFilter(request, response);
        logResponseHeaders(response);
    }

    private void logResponseHeaders(HttpServletResponse response) {
        Collection<String> headerNames = response.getHeaderNames();
        StringBuilder sb = new StringBuilder("响应头: ");
        for (String headerName : headerNames) {
            sb.append("[").append(headerName).append(": ").append(response.getHeader(headerName)).append("] ");
        }
        log.debug(sb.toString());
    }
}